package com.base.common.coder;

import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yanjiaqiang
 * @date 2011-1-7
 * @version $Id: KeyValueMapCoder.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class KeyValueMapCoder implements BiCoder<Map<String, String>, String> {

	private char itemSeperator;

	private char keyValueSeperator;

	public KeyValueMapCoder(char itemSeperator, char keyValueSeperator) {
		super();
		this.itemSeperator = itemSeperator;
		this.keyValueSeperator = keyValueSeperator;
	}

	@Override
	public Map<String, String> decode(String input) {
		if (input == null)
			return null;

		char[] chs = input.toCharArray();
		int len = input.length();

		Map<String, String> map = new HashMap<String, String>();

		int pos = 0;
		String key = null;

		for (int i = 0; i < len; i++) {
			char ch = chs[i];
			if (ch == keyValueSeperator) {

				if (pos == i) {
					// 防止这类的出现"a=A&b=c&b&=C"
					throw new RuntimeException();
				}

				if (key != null) {
					// 为了防止 “a=A b=b&c=C”
					throw new RuntimeException();
				} else {
					key = new String(chs, pos, i - pos);
				}
				pos = i + 1;
			}

			if (ch == itemSeperator) {
				if (pos == i) {
					throw new RuntimeException();
				}
				String value = new String(chs, pos, i - pos);
				map.put(key, value);
				key = null;
				pos = i + 1;
			}
		}

		if (pos < len) {
			// 让"a=A&b=B&c=C&"能通过
			String value = new String(chs, pos, len - pos);
			map.put(key, value);

		} else if (pos == len) {
			if (key != null) {
				// 防止"a=A&b=B&c="
				throw new RuntimeException();
			}
		}

		return map;

	}

	@Override
	public String encode(Map<String, String> input) {
		if (input == null || input.size() == 0) {
			return "";
		}

		// 故意多分配一个char，为了是方便后面的map遍历处理
		CharBuffer buffer = CharBuffer.allocate(input.size() * 4);

		for (Map.Entry<String, String> entry : input.entrySet()) {
			buffer.put(entry.getKey());
			buffer.put(keyValueSeperator);
			buffer.put(entry.getValue());
			buffer.put(itemSeperator);
		}

		char[] chs = buffer.array();

		// 把最后的itemSeperator去掉。
		return new String(chs, 0, chs.length - 1);
	}

}
